#include <JXRGlue.h>
#include <stdio.h>
#include <stdint.h>

size_t jxr_encode(U16 height, U16 width, U8 quality, void **buf, size_t *buf_size, void* outbuf, size_t* outdatalen)
{
	size_t outbuf_size = 2*width*height;

    U8 res_x = 92;
    U8 res_y = 92;
    U16 stride = 2*width; // bytes per pixel hardcoded for uint16: 2

    ERR                 err;
    PKFactory*          factory = NULL;
    struct WMPStream*   stream;
    PKCodecFactory*     codec_factory = NULL;
    PKImageEncode*      encoder = NULL;
    CWMIStrCodecParam   wmiSCP;

	PKPixelFormatGUID pixel_format;
	pixel_format = GUID_PKPixelFormat16bppGray;

    Call(PKCreateFactory(&factory, PK_SDK_VERSION));
    Call(PKCreateCodecFactory(&codec_factory, WMP_SDK_VERSION));    
    Call(factory->CreateStreamFromMemory(&stream, outbuf, outbuf_size));

    Call(codec_factory->CreateCodec(&IID_PKImageWmpEncode, (void**)&encoder));

    // options hardcoded
    memset(&wmiSCP, 0, sizeof(wmiSCP));
	wmiSCP.bVerbose = TRUE;
	wmiSCP.bdBitDepth = BD_16;
	wmiSCP.bfBitstreamFormat = FREQUENCY;
	wmiSCP.bProgressiveMode = TRUE;    
	wmiSCP.sbSubband = SB_ALL;
	wmiSCP.cfColorFormat = Y_ONLY;
	wmiSCP.uiDefaultQPIndex = quality;
	wmiSCP.olOverlap = OL_NONE;

    Call(encoder->Initialize(encoder, stream, &wmiSCP, sizeof(wmiSCP)));

    Call(encoder->SetPixelFormat(encoder, pixel_format));
    Call(encoder->SetSize(encoder, width, height));
    Call(encoder->SetResolution(encoder, res_x, res_y));

    Call(encoder->WritePixels(encoder, height, *buf, stride));

    outbuf_size = encoder->WMP.nCbImage+encoder->WMP.nOffImage;

	//replace buffer and free memory
	*outdatalen = outbuf_size;

    Cleanup:
		printf("error code at the end of encode: %d",err);
        if (encoder)
            encoder->Release(&encoder);
        
        if (codec_factory)
            codec_factory->Release(&codec_factory);
        
        if (factory)
            factory->Release(&factory);
        
    return 1;
}
